#!/bin/bash
#backupXWiki.sh
#
#This script gets a backup from an XWiki site.
#An argument can optionally be given to specify the directory you want the backup to be saved to.
#Create a file in the same directory called auth.txt, this should contain the following format:
#user=<USER>
#password=<PASSWORD>
#site=http://site.myxwiki.org
#
#Where <USER> and <PASSWORD> are a valid administrator username and password for the specified XWiki.
#Be sure to change the permissions on this file so that it is not world readable.
#DO NOT USE THIS ON AN UNTRUSTED MACHINE
#Script written by Ben Falconer 7/08/08

#Save the directory where the script is running for temporary files
script_dir=$(dirname $0)
output=$(date +%d_%m_%Y_backup.xar)
if [ -n "$1" ]; then
	out_dir=$1
	if ! [ -d $out_dir ]; then
		mkdir $out_dir
	fi
else
	out_dir=$script_dir
fi
#Check that the auth.txt exists and read from it
if [ -e $script_dir/auth.txt ]; then
	source $script_dir/auth.txt
#Get login cookies for the specified XWiki
	wget --cookies=on --keep-session-cookies --save-cookies=$script_dir/cookies.txt "$site/xwiki/bin/loginsubmit/XWiki/XWikiLogin" --post-data="j_username=$user&j_password=$password" -P $script_dir --no-verbose
#Check that the details worked
	if [ -e $script_dir/WebHome ]; then
		rm $script_dir/WebHome
		echo "Successfully authenticated."
#Try to download the backup
		wget --cookies=on --load-cookies=$script_dir/cookies.txt "$site/xwiki/bin/export/XWiki/Export?name=&history=true&backup=true" -O $out_dir/$output --no-verbose
#Check that everything worked properly
		if [ $? -eq 0 ]; then
			if grep -q "Admin Rights are needed for this function" $out_dir/$output; then
				echo "The account specified in $script_dir/auth.txt does not appear to have administrative rights on the specified XWiki"
				rm $out_dir/$output
			else
				echo "Backup successful!"
#Optionally chmod the file so its world readable, mostly in case you want to automate the script.
#				chmod a+r $out_dir/$output
			fi
		else
			echo "There was a problem while downloading from $site, the connection may have dropped"
			rm $out_dir/$output
		fi
		rm $script_dir/cookies.txt
	else
		echo "There was a problem authorizing your details, check the username and password in auth.txt are correct."
		rm $script_dir/cookies.txt
	fi
#if auth.txt doesn't exist prompt the user to create it
else
	echo "Please create a file in the same directory named auth.txt,"
	echo "this should contain the following format:"
	echo "user=<USER>"
	echo "password=<PASSWORD>"
	echo "site=http://site.myxwiki.org"
	echo
	echo "Where <USER> and <PASSWORD> are a valid administrator username and password for the specified XWiki."
fi

